package com.itlaobing.exam.handler;

import com.itlaobing.exam.entity.UserRole;
import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.TypeHandler;
import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class UserRoleHandler implements TypeHandler<UserRole> {
    private static final Logger logger = LogManager.getLogger( UserRoleHandler.class );

    @Override
    public void setParameter(PreparedStatement ps, int index, UserRole role, JdbcType jdbcType) throws SQLException {
        logger.info( "将枚举常量转换成数据库表中可以存储的整数值" );
        switch (role){
            case ADMIN:ps.setInt( index , 0 ); break;
            case STUDENT:ps.setInt( index , 1 ); break;
            case TEACHER:ps.setInt( index , 2 ); break;
        }
    }

    @Override
    public UserRole getResult( ResultSet rs, String label ) throws SQLException {
        logger.info( "将结果集中的整数值转换成相应的枚举常量" );
        int ordinal = rs.getInt( label );
        return this.of( ordinal );
    }

    @Override
    public UserRole getResult( ResultSet rs , int index ) throws SQLException {
        logger.info( "将结果集中的整数值转换成相应的枚举常量" );
        int ordinal = rs.getInt( index );
        return this.of( ordinal );
        }
        @Override public UserRole getResult( CallableStatement cs , int index ) throws SQLException {
        logger.info( "将由存储过程的传出参数传出的整数值转换成相应的枚举常量" );
        int ordinal = cs.getInt( index );
        return this.of( ordinal );
    }

    private UserRole of( int ordinal ) {
        UserRole role = null ;
        switch ( ordinal ) {
            case 0 : role = UserRole.ADMIN ; break ;
            case 1 : role = UserRole.TEACHER ; break ;
            case 2 : role = UserRole.STUDENT ; break ;
        }
        return role;
    }
}
